#ifndef CCONTROLCONNECTION_H_
#define CCONTROLCONNECTION_H_

#include <es_sock.h>
#include <in_sock.h>
#include <e32svr.h>
#include <btdevice.h>

#include "CDataConnection.h"
#include "CConfig.h"
#include "Common.h"
#include "CBTEngine.h"


#ifndef __EMULATOR
	#include "CGprsEngine.h"
#else
	#include "CGprsEmulator.h"
#endif */

#ifdef __LOGGER
	#include <flogger.h>
#endif

enum TControlConnectionProgress 
{
	EIdle,
	EConnecting,
	ESending,
	EReceiving, //Receive a chunk
	EReceived,	//Receive the whole command message
	EReconnecting,
	EManuallyConnected
} ;

class CControlConnection:public CActive
{
public:

	static CControlConnection* NewL(CConfig& aConfig, MDisplayObserver& aDisplay);
	CControlConnection(CConfig& aConfig, MDisplayObserver& aDisplay);
	virtual ~CControlConnection();	
	TInt Start();
	void Stop();
	
	TInt StartManually();
	void StopManually();	
	TBool isStarted();

	void setDataConnectionParameters(const TDesC* aDataServerName, TUint aNodeid , TUint aDataPort , TUint aDataInterval);
	void setGpsParameters(const TBTDevAddr& aAddr, const TUint& aPort);
	void setGprsParameters(const TUint& aIAP);
	CBTEngine* getBtEngine();
	
//Private methods
private:

	void ConstructL(CConfig& aConfig);
	//CActive methods
	void DoCancel(); 
    void RunL();

    void OpenConnection();
	void CloseConnection();
	void SendMessage();
	void SendChunkMessageL(); //It's used in "history" command
	void WaitForAMessage();
	void ManageChunks();
	void DoCommandL();
	//From aMessage="interval 600" returns 600
	TInt get_interval_from_command(TDesC &aMessage);

//Private Data
private:
	
	//Constructor argument
	CConfig& iConfig;
	MDisplayObserver& iDisplay;
	
	RSocketServ* iSocketServ;
	TUint iIAP;
	RSocket iSocket;
	TBuf<SERVERNAMELENGTH> iServerName;
	TNameEntry iHostAddress ;
	TUint iPort;
	TControlConnectionProgress iState;
	
	TBuf<256> iMessage; //Buffer for receiving messages.
	TBuf8<64> iResponseChunk;
	TSockXfrLength iResponseChunkSizePkg;
	
	TInetAddr iAddress;
	
	TBuf8<256> iMessageToSend;
	RTimer iTimmer; // For count the timing of reconnection when the connection fails.
	TUint iIintervalReconnection;
		
	#ifdef __EMULATOR
		CGprsEmulator* iGprsEngine;
	#else
		CGprsEngine* iGprsEngine;
	#endif

	/* Data connection */
	CDataConnection* iDataConnection;
	TUint iNodeid;
	TBuf<SERVERNAMELENGTH> iDataServerName;
	TUint iDataPort;
	TUint iDataInterval;
	
	/* GPS */
	CBTEngine* iBtEngine;
	TBTDevAddr iGpsAddr;
	TUint iGpsPort;
	
	
	#ifdef __LOGGER
		RFileLogger iLog;
	#endif
	
};

#endif /*CCONTROLCONNECTION_H_*/
